package com.rykj.qxj.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.rykj.qxj.server.util.DES;

public class NamedParameterJdbcTemplateUtil {
	private static Logger logger = LoggerFactory.getLogger(NamedParameterJdbcTemplateUtil.class);
	
	private static final String DRIVER_CLASSNAME ="com.mysql.jdbc.Driver";
	
	public static NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(String ip, String port, String databaseName,
			String userName, String password) {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(DRIVER_CLASSNAME);
		dataSource.setUrl("jdbc:mysql://" + ip + ":" + port + "/" + databaseName + "?characterEncoding=utf8");
		dataSource.setUsername(userName);
		dataSource.setPassword(new DES().decode(password));
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
		return namedParameterJdbcTemplate;
		
		/*DruidDataSource dataSource = getDataSourceByDruid(ip,port,databaseName,userName,password);
		logger.info("====dataSource===="+dataSource);
		logger.info("====dataSource.getInitialSize===="+dataSource.getInitialSize());
		try {
			logger.info("====dataSource.getConnection===="+dataSource.getConnection());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		logger.info("====dataSource.getInitialSize===="+dataSource.getInitialSize());
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
		return namedParameterJdbcTemplate;*/
	}
	private static DruidDataSource getDataSourceByDruid(String ip, String port, String databaseName,
			String userName, String password) {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(DRIVER_CLASSNAME); 
		dataSource.setUsername(userName); 
		dataSource.setPassword(new DES().decode(password)); 
		dataSource.setUrl("jdbc:mysql://" + ip + ":" + port + "/" + databaseName + "?characterEncoding=utf8");
	    //初始化时建立物理连接个数
		dataSource.setInitialSize(1); 
		//最大连接池数量
		dataSource.setMaxActive(20);
		//最小连接池数量
		dataSource.setMinIdle(1);
		//获取连接时最大等待时间，单位毫秒
		dataSource.setMaxWait(3000);
		//建议配置为true，不影响性能，并且保证安全性。申请连接的时候检测，如果空闲时间大于timeBetweenEvictionRunsMillis，执行validationQuery检测连接是否有效。
		dataSource.setTestWhileIdle(true);
		return dataSource;
	}
}
